package com.tiyende.kash.loop.ui.fragment

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Typeface
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.graphics.toColorInt
import com.lib.common.permission.CommonPermissions
import com.lib.common.permission.OnPermissionCallback
import com.lib.common.permission.Permission
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.common.CommonFragment
import com.tiyende.kash.loop.configs.TiyendeApiPath
import com.tiyende.kash.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.kash.loop.databinding.TiyendeFragmentAuthenticationStepSelfieInfoBinding
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.activity.TiyendeAuthenticationStepsActivity
import com.tiyende.kash.loop.ui.activity.TiyendeCameraSelfieActivity
import com.tiyende.kash.loop.ui.dialog.TiyendePermissionReasonDialog
import com.tiyende.kash.loop.ui.dialog.TiyendeSuccessDialog
import com.tiyende.kash.loop.utils.TiyendeImageUtil
import com.tiyende.kash.loop.utils.helper.TiyendePermissionHelper
import com.tiyende.kash.loop.utils.log.TiyendeLogger
import com.tiyende.kash.loop.utils.track.TrackPointManager
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/22 13:40
 * @Annotation：认证流程 - 自拍照
 */
class TiyendeAuthenticationStepSelfieFragment(): CommonFragment() {
    private var _binding: TiyendeFragmentAuthenticationStepSelfieInfoBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "tiyende kash step selfie binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var stepItem: JSONObject? = null
    private var stepTitle = ""
    //是否选中删除信息,默认选中
    private var isShowDelete = true

    //本地预览地址
    private var faceImgPath = ""
    //拍摄的头像地址
    private var faceImgUrl = ""

    private var checkButtonCallback: ((String) -> Unit)? = null
    constructor(stepItem: JSONObject,callBack: (String) -> Unit): this(){
        this.stepItem = stepItem
        this.checkButtonCallback = callBack
        stepTitle = stepItem.optString("stepTitle")
    }

    companion object {
        fun newInstance(stepItem: JSONObject,callBack: (String) -> Unit): TiyendeAuthenticationStepSelfieFragment {
            return TiyendeAuthenticationStepSelfieFragment(stepItem, callBack)
        }
    }

    override fun getTiyendeRootView(inflater: LayoutInflater): View {
        _binding = TiyendeFragmentAuthenticationStepSelfieInfoBinding.inflate(inflater)
        return binding.root
    }

    override fun initTiyendeView() {
        initSelfieUploadCreditLimitApprovedTipsText()
        showTiyendeSelfieBeforeView()

        isShowDelete = true
        showTiyendeSelfieDeleteTips()

        //提交按钮移到外层，通过通知的方式控制提交
        _binding?.btnStartOrSubmit?.visibility = View.INVISIBLE
    }

    override fun initTiyendeListener() {
        _binding?.selfieDeleteLayout?.setOnClickListener {
            isShowDelete = !isShowDelete
            showTiyendeSelfieDeleteTips()
        }
        _binding?.selfieMaskLayout?.setOnClickListener {
            _binding?.imgSelfieDefault?.callOnClick()
        }
        _binding?.imgSelfieDefault?.setOnClickListener{
            if (CommonPermissions.isGranted(requireContext(),Permission.CAMERA)){
                startOpenCameraAction()
            } else {
                showTiyendePermissionReasonDialog()
            }
        }
        _binding?.imgSelfie?.setOnClickListener {
            _binding?.imgSelfieDefault?.callOnClick()
        }
        //提交
        _binding?.btnStartOrSubmit?.setOnClickListener{
            onTiyendeSubmitAuthenticationInfoAction()
        }
    }

    override fun loadTiyendeData() {
        addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_START,stepTitle))
    }

    private fun initSelfieUploadCreditLimitApprovedTipsText(){
        val showApprovedKey1 = getString(R.string.tiyende_selfie_approved_tips_over)
        val showApprovedKey2 = getString(R.string.tiyende_selfie_approved_tips_past_days)
        val showApprovedText = String.format(getString(R.string.tiyende_selfie_approved_tips),showApprovedKey1,showApprovedKey2)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val startApprovedIndex2 = showApprovedText.indexOf(showApprovedKey2)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan("#FF3ED9AB".toColorInt()), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(ForegroundColorSpan("#FF3ED9AB".toColorInt()), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textSelfieApproved?.text = approvedTipsSpannable
    }

    /**
     * 人脸拍照
     */
    private val selfieCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                result.data?.let {
                    val faceImgPath = it.getStringExtra("imgLocalPath").toString()
                    TiyendeLogger.e(">>>>>>>>>face info ：$faceImgPath")
                    val imgLocalPath = it.getStringExtra("imgLocalPath").toString()
                    val imgUrl = it.getStringExtra("imgUrl").toString()
                    showTiyendeSelfieAfterView(imgLocalPath,imgUrl)
                }
            }
        }
    }

    private fun showTiyendeSelfieDeleteTips(){
        when(isShowDelete){
            true -> {
                _binding?.imgSelectDelete?.setImageResource(R.mipmap.tiyende_selfie_delete_tips_selected_icon)
            }
            else -> {
                _binding?.imgSelectDelete?.setImageResource(R.mipmap.tiyende_selfie_delete_tips_normal_icon)
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showTiyendeSelfieBeforeView(){
        faceImgPath = ""
        faceImgUrl = ""
        _binding?.imgSelfie?.visibility = View.GONE
        _binding?.selfieMaskLayout?.visibility = View.GONE
        _binding?.imgSelfieDefault?.visibility = View.VISIBLE
        _binding?.btnStartOrSubmit?.text = getString(R.string.tiyende_selfie_start)
        checkButtonCallback?.invoke(getString(R.string.tiyende_selfie_start))
    }

    /**
     * 显示拍照之后的View
     */
    private fun showTiyendeSelfieAfterView(imgPath: String, imgUrl: String){
        faceImgPath = imgPath
        faceImgUrl = imgUrl
        _binding?.let { binding ->
            TiyendeImageUtil.instance?.loadImageUrl(requireContext(),binding.imgSelfie,faceImgPath)
            binding.imgSelfie.visibility = View.VISIBLE
            binding.selfieMaskLayout.visibility = View.VISIBLE
            _binding?.imgSelfieDefault?.visibility = View.GONE
            binding.btnStartOrSubmit.text = getString(R.string.tiyende_selfie_confirm)
            checkButtonCallback?.invoke(getString(R.string.tiyende_selfie_confirm))
            val eventRemark = "$stepTitle $$$imgUrl"
            addEventPointRequestAction(TiyendeEventPointType.FORM.TIYENDE_FORM_UPLOAD_URL,eventRemark)
        }
    }

    /**
     * 显示权限描述文案
     */
    private fun showTiyendePermissionReasonDialog(){
        val item = TiyendePermissionHelper.queryTiyendeCameraItem()
        val requestPermission = item.optString("permission")
        val dialog = TiyendePermissionReasonDialog(requireContext(),stepTitle,object : TiyendePermissionReasonDialog.IDialogCallback{
            override fun onTiyendePermissionDenyClick() {
                addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_DENY, requestPermission)
            }
            override fun onTiyendePermissionAgreeClick() {
                addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_AGREE, requestPermission)
                requestTiyendePermissionAction()
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.showTiyendePermissionReasonItem(item)
    }

    /**
     * 申请权限
     */
    private fun requestTiyendePermissionAction(){
        CommonPermissions.with(this)
            .permission(Permission.CAMERA)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        startOpenCameraAction()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    CommonPermissions.startPermissionActivity(requireContext(),Permission.CAMERA)
                }
            })
    }

    /**
     * 发送成功提示
     */
    private fun showSelfieDeleteTipsDialog(params: JSONObject){
        val sendSuccessDialog = TiyendeSuccessDialog(requireContext())
        sendSuccessDialog.setCancelable(true)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.showSuccessTips(getString(R.string.tiyende_selfie_delete_success_tips))
        Handler(Looper.getMainLooper()).postDelayed({
            if (isAdded && !requireActivity().isFinishing && sendSuccessDialog.isShowing) {
                sendSuccessDialog.dismiss()
            }
            submitTiyendeSelfieAction(params)
        },2000)
    }

    /**
     * 打开相机
     */
    private fun startOpenCameraAction(){
        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_SELFIE_START_TAKE)
        val intent = Intent(context, TiyendeCameraSelfieActivity::class.java)
        intent.putExtra("pageName",stepTitle)
        selfieCameraResultLauncher.launch(intent)
    }

    /**
     * 提交
     */
    private fun submitTiyendeSelfieAction(params: JSONObject){
        val act = getAct() as TiyendeAuthenticationStepsActivity
        act.onAuthenticationStepSubmitAction(params)
    }

    /**
     * 提交进件信息
     */
    private fun onTiyendeSubmitAuthenticationInfoAction(){
        //开始人脸拍照
        if (faceImgUrl.isEmpty()){
            _binding?.imgSelfieDefault?.callOnClick()
            return
        }
        //提交
        val params = JSONObject().addCommonParams().apply {
            put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_OCR_INFO_PATH)
            put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE、NONE）
            put("faceImgUrl",faceImgUrl)//人脸图片
        }
        TiyendeLogger.e(">>>>>>>selfie>>>>>>params ：$params")
        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_SELFIE_CONFIRM_SUBMIT)
        // TODO: 进件信息点下一步 需上报所有埋点
        TrackPointManager.getInstance().manualReport()

        if (isShowDelete){
            showSelfieDeleteTipsDialog(params)
        } else {
            submitTiyendeSelfieAction(params)
        }
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_SUBMIT_AUTHENTICATION -> {
                onTiyendeSubmitAuthenticationInfoAction()
            }
            else -> {

            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_END,stepTitle))
    }
}